package com.wei800.turnover.config.mybatis.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class YootkPointTypeHandler extends BaseTypeHandler<Point> {
    private final GeometryFactory geometryFactory = new GeometryFactory();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Point parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.toText()); // 将 Point 转为 WKT 格式
    }

    @Override
    public Point getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String wkt = rs.getString(columnName);
        if (wkt != null) {
            try {
                return (Point) new WKTReader(geometryFactory).read(wkt); // 从 WKT 格式构建 Point
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    @Override
    public Point getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String wkt = rs.getString(columnIndex);
        if (wkt != null) {
            try {
                return (Point) new WKTReader(geometryFactory).read(wkt);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    @Override
    public Point getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String wkt = cs.getString(columnIndex);
        if (wkt != null) {
            try {
                return (Point) new WKTReader(geometryFactory).read(wkt);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}